import { createRouter, createWebHistory } from 'vue-router'
import { useUserInfo } from '@/stores/userInfo'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/loginPage.vue')
    },
    {
      path: '/home',
      name: 'home',
      component: () => import('../views/homePage.vue'),
      children: [
        { path: 'index', name: 'index', component: () => import('../views/homepageIndex.vue') },
        { path: 'swiper', name: 'swiper', component: () => import('../views/homePageSwiper.vue') },
        { path: 'users', name: 'users', component: () => import('../views/homePageUser.vue') },
        { path: 'video', name: 'video', component: () => import('../views/homepageVideos.vue') },
        { path: 'class', name: 'class', component: () => import('../views/homePageClass.vue') },
        { path: 'reptile', name: 'reptile', component: () => import('../views/homePageReptile.vue') },
        { path: 'version', name: 'version', component: () => import('../views/homePageVersion.vue') }
      ]
    },
    {
      path: '/:pathMatch(.*)',
      redirect: '/'
    }
  ]
})

router.beforeEach(async to => {
  if (to.matched[0]['name'] == 'home') {
    let pass = false
    try {
      const userInfo = useUserInfo()
      if (await userInfo.getUserInfo()) pass = true
    } catch (error) {
      pass = false
    }
    if (!pass) {
      return '/'
    }
  }
})

export default router
